<script setup lang="ts">
import { ref, watch } from "vue";
import { ElCard, ElText } from "element-plus";

import {graphic} from "echarts"
import Echart from "./Echart.vue";
import { THomeChart } from "@/global";


const props = defineProps<{
  data?: THomeChart["goods_rank"];
}>();

const options = ref<Record<string, any>>({
  grid: {
    top: "40px",
    right: 10,
    bottom: 10,
    left: "70px",
  },
  tooltip: {
    // show: false,
    trigger: "item",
    // formatter: (params: any) => `<div style="display: flex;">

    // <span style="max-width:30px; word-break: break-all;">${params.name}</span>
    // <span style="margin-left: 20px">${params.value}</span>

    // </div>`,
    textStyle: {
      width: 100,
      // overflow: "truncate",
    },
  },

  legend: {
    top: "5%",
    left: "center",
    show: false,
  },

  xAxis: {
    type: "value",
    axisLine: {
      show: false,
    },
    // boundaryGap: [0, 0.01],
  },

  yAxis: {
    type: "category",
    axisTick: {
      show: false,
    },
    axisLine: {
      show: false,
    },
    axisLabel: {
      rotate: 45,
      width: 80,
      overflow: "truncate",
    },
  },
  series: [
    {
      // name: "goodsRank",
      type: "bar",
      avoidLabelOverlap: false,
      barMaxWidth: "30px",
      itemStyle: {
        color: new graphic.LinearGradient(1, 1, 0, 1, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#188df0' },
          { offset: 1, color: '#188df0' }
        ])
      },
    },
  ],
});

watch(
  () => props.data,
  (data) => {
    if (data) {
      // const total = data?.reduce((sum, item) => {
      //   return sum + item.num;
      // }, 0 as number);

      options.value = {
        xAxis: {
          type: "value",
          position: "top",
          // boundaryGap: [0, 0.01],
        },
        yAxis: {
          type: "category",
          data: data.map((e) => e.goods_name),
        },
        series: [
          {
            // name: "goodsRank",
            data,
          },
        ],
      };
    }
  }
);

const colors = ref<string[]>([]);
const handleInit = (ins: any) => {
  colors.value = ins.getOption().color as string[];
};
</script>
<template>
  <ElCard>
    <template #header>
      <div class="mb-2">统计占比</div>
      <div class="text-lg font-bold">单品收藏排行</div>
    </template>

    <Echart class="w-full h-[500px]" :options="options" @init="handleInit" />

    <!-- <div class="max-w-[240px] mx-auto">
      <template v-for="(item, index) in data" :key="index">
        <div class="flex items-center my-3 px-3">
          <span
            class="mr-2 w-[10px] h-[10px] rounded-full"
            :style="{ background: colors[index] }"
          />
          <div class="flex-auto w-[50%]">
            <ElText truncated>{{ item.goods_name }}</ElText>
          </div>
          <div class="flex-none text-sm ml-3">{{ item.num }}</div>
        </div>
      </template>
    </div> -->
  </ElCard>
</template>
